// 权限控制工具
const TOKEN_KEY = 'sciif_token'
const USER_INFO_KEY = 'sciif_user_info'

// 安全的JSON解析函数
export function safeJSONParse(str, defaultValue = null) {
  if (!str || str === 'undefined' || str === 'null') {
    return defaultValue
  }
  try {
    return JSON.parse(str)
  } catch (error) {
    console.warn('JSON解析失败:', error, '原始数据:', str)
    return defaultValue
  }
}

// 获取token
export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

// 设置token
export function setToken(token) {
  localStorage.setItem(TOKEN_KEY, token)
}

// 移除token
export function removeToken() {
  localStorage.removeItem(TOKEN_KEY)
}

// 获取用户信息
export function getUserInfo() {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return safeJSONParse(userInfo, null)
}

// 设置用户信息
export function setUserInfo(userInfo) {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

// 移除用户信息
export function removeUserInfo() {
  localStorage.removeItem(USER_INFO_KEY)
}

// 检查是否已登录
export function isLoggedIn() {
  return !!getToken()
}

// 检查用户权限
export function hasPermission(permission) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.permissions) return false
  return userInfo.permissions.includes(permission)
}

// 检查用户角色
export function hasRole(role) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.roles) return false
  return userInfo.roles.includes(role)
}

// 登出
export function logout() {
  removeToken()
  removeUserInfo()
  window.location.href = '/'
}

// 管理端相关函数
export function getAdminToken() {
  return localStorage.getItem('adminToken')
}

export function getAdminUser() {
  const adminUser = localStorage.getItem('adminUser')
  return safeJSONParse(adminUser, {})
}

export function getAdminPermissions() {
  const adminPermissions = localStorage.getItem('adminPermissions')
  return safeJSONParse(adminPermissions, { roles: [], resources: [] })
}

// 清除所有管理端数据
export function clearAdminData() {
  localStorage.removeItem('adminToken')
  localStorage.removeItem('adminUser')
  localStorage.removeItem('adminPermissions')
  localStorage.removeItem('adminUserInfo')
}

// 检查管理端token是否有效
export function isAdminTokenValid() {
  const adminToken = getAdminToken()
  if (!adminToken) return false
  
  try {
    const tokenPayload = JSON.parse(atob(adminToken.split('.')[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    return tokenPayload.exp && tokenPayload.exp > currentTime
  } catch (error) {
    return false
  }
}

// 管理端登出
export function adminLogout() {
  clearAdminData()
  window.location.href = '/admin/login'
} 